package com.sapp.imagecolorization.notification

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.sapp.imagecolorization.R

class Notification {
    private val PROGRESS_MAX = 100
    private val PROGRESS_CURRENT = 0

    fun showDownloadingNotification(context: Context, imagePath: String, notifyId: Int) {
        val name = "MyNotifications"
        val descriptionText = "Channel description"
        val importance = NotificationManager.IMPORTANCE_HIGH

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create the NotificationChannel
            val mChannel = NotificationChannel("MyNotifications", name, importance)
            mChannel.description = descriptionText
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            val notificationManager =
                context.getSystemService(AppCompatActivity.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(mChannel)
        }

        val notificationIntent = Intent()

        notificationIntent.type = "image/*"
        notificationIntent.action = Intent.ACTION_GET_CONTENT

        val contentIntent = PendingIntent.getActivity(
            context,
            0, notificationIntent,
            0
        )

        val builder = NotificationCompat.Builder(context, "MyNotifications")
            .setContentTitle("Image downloading...")
            .setAutoCancel(true)
            .setContentText("Download in progress")
            .setSmallIcon(R.drawable.ic_download_active)
            .setDefaults(Notification.DEFAULT_ALL)
            .setPriority(NotificationManager.IMPORTANCE_HIGH)
            .setContentIntent(contentIntent)
            .setWhen(System.currentTimeMillis())


        NotificationManagerCompat.from(context).apply {
            // Issue the initial notification with zero progress
            builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
            notify(notifyId, builder.build())

            // When done, update the notification one more time to remove the progress bar
            builder.setContentText("Download complete")
                .setProgress(0, 0, false)
            notify(notifyId, builder.build())
        }
        val notification = builder.build()
        val notificationManager = NotificationManagerCompat.from(context)

        notification.flags = notification.flags or Notification.FLAG_AUTO_CANCEL
        notificationManager.notify(notifyId, notification)
    }

}